package com.party.mobile.web.controller.copartner;

import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.model.copartner.BrokerageItem;
import com.party.core.model.copartner.BrokerageListOutput;
import com.party.core.model.copartner.BrokerageStatusEnum;
import com.party.core.model.member.Member;
import com.party.core.model.wallet.Withdrawals;
import com.party.core.service.copartner.IBrokerageItemService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.wallet.IWithdrawalService;
import com.party.core.service.wallet.biz.WithdrawalsBizService;
import com.party.mobile.biz.copartner.BrokerageBizService;
import com.party.mobile.biz.crowdfund.ProjectBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.brokerage.output.BrokerageDetailOutput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: Administrator.
 * @Description: 佣金
 * @Date:Created in 2017/10/25 0025 下午 14:53.
 */
@Controller
@Authorization
@RequestMapping("copartner/brokerage")
public class BrokerageController {
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private IBrokerageItemService brokerageItemService;
    @Autowired
    private IWithdrawalService withdrawalService;
    @Autowired
    private WithdrawalsBizService withdrawalsBizService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private ProjectBizService projectBizService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private BrokerageBizService brokerageBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 佣金流水
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("brokerageList")
    public AjaxResult brokerageList(HttpServletRequest request, Page page) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        List<BrokerageListOutput> listOutput = brokerageItemService.brokerageList(new BrokerageItem(currentUser.getId()), page);
        return AjaxResult.success(listOutput, page);
    }

    /**
     * 佣金流水
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("newBrokerageList")
    public AjaxResult newBrokerageList(HttpServletRequest request, Page page, String memberId) {
        try {
            if (StringUtils.isEmpty(memberId)) {
                CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
                memberId = currentUser.getId();
            }

            BrokerageItem btobj = new BrokerageItem();
            btobj.setPartnerId(memberId);
            List<BrokerageListOutput> listOutput = brokerageItemService.newBrokerageList(btobj, page);
            return AjaxResult.success(listOutput, page);
        } catch (Exception e) {
            logger.error("佣金流水异常", e);
            return AjaxResult.error(100, "佣金流水异常");
        }
    }

    /**
     * 佣金流水
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("v2/newBrokerageList")
    public AjaxResult newBrokerageListV2(HttpServletRequest request, Page page, String memberId) {
        try {
            if (StringUtils.isEmpty(memberId)) {
                CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
                memberId = currentUser.getId();
            }

            BrokerageItem btobj = new BrokerageItem();
            btobj.setPartnerId(memberId);
            List<BrokerageListOutput> listOutput = brokerageItemService.newBrokerageList(btobj, page);

            listOutput.forEach(output -> {
                if (!BrokerageStatusEnum.TWO_REJECT.getCode().equals(output.getCheckStatus())) {
                    if (null == output.getWithdrawDate() || output.getWithdrawDate().after(new Date())) {
                        output.setCheckStatus(2);
                    } else if (output.getWithdrawDate().before(new Date())) {
                        output.setCheckStatus(1);
                    }
                }
            });
            return AjaxResult.success(listOutput, page);
        } catch (Exception e) {
            logger.error("佣金流水异常", e);
            return AjaxResult.error(100, "佣金流水异常");
        }
    }

    /**
     * 佣金数字：累计佣金/未结算佣金
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("newBrokerageNumber")
    public AjaxResult newBrokerageNumber(HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            Map<String, Object> brokerageData = brokerageBizService.getBrokerageData(currentUser.getId());
            return AjaxResult.success(brokerageData);
        } catch (Exception e) {
            logger.error("合伙人数据异常", e);
            return AjaxResult.error(100, "合伙人数据异常");
        }
    }

    /**
     * 提现流水
     *
     * @param request
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("withdrawalList")
    public AjaxResult withdrawalList(HttpServletRequest request, Page page) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            Withdrawals withdrawal = new Withdrawals();
            withdrawal.setCreateBy(currentUser.getId());
            withdrawal.setType(Withdrawals.TYPE_BROKERAGE);
            List<Withdrawals> withdrawals = withdrawalService.listPage(withdrawal, page);
            return AjaxResult.success(withdrawals, page);
        } catch (Exception e) {
            logger.error("佣金提现列表异常", e);
            return AjaxResult.error(100, "佣金提现列表异常");
        }
    }

    /**
     * 佣金数字：累计佣金/未结算佣金
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("brokerageNumber")
    public AjaxResult brokerageNumber(HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        Map<String, Object> resultMap = Maps.newHashMap();

        // 累计佣金（可提现/已冻结）
        Double brokerageTotal = brokerageItemService.getSumTotal(currentUser.getId(), 1);
        resultMap.put("brokerageTotal", BigDecimalUtils.round(brokerageTotal, 2));

        // 累计提现佣金
        Double withdrawalTotal = withdrawalsBizService.getWithdrawalTotal(currentUser.getId(), Withdrawals.TYPE_BROKERAGE,null);
        resultMap.put("withdrawalTotal", BigDecimalUtils.round(withdrawalTotal, 2));

        // 可结算佣金 = 累计佣金（可提现） - 累计提现佣金
        Double brokerageTotal2 = brokerageItemService.getSumTotal(currentUser.getId(), 2);
        if (brokerageTotal2 != 0d) {
            double subTotal2 = BigDecimalUtils.sub(brokerageTotal2, withdrawalTotal);
            resultMap.put("canBrokerageTotal", BigDecimalUtils.round(subTotal2, 2));
        } else {
            resultMap.put("canBrokerageTotal", brokerageTotal2);
        }

        // 未结算佣金 = 累计佣金（已冻结）
        Double brokerageTotal3 = brokerageItemService.getSumTotal(currentUser.getId(), 3);
        if (brokerageTotal3 != 0d) {
            //double subTotal3 = BigDecimalUtils.sub(brokerageTotal3, withdrawalTotal);
            resultMap.put("remainBrokerageTotal", BigDecimalUtils.round(brokerageTotal3, 2));
        } else {
            resultMap.put("remainBrokerageTotal", brokerageTotal3);
        }

        return AjaxResult.success(resultMap);
    }

    /**
     * 佣金详情
     *
     * @param id 佣金id
     * @return
     */
    @ResponseBody
    @RequestMapping("detail")
    public AjaxResult detail(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "id不能为空");
        }
        try {
            Map<String, Object> resultMap = brokerageItemService.getItemDetail(id);
            BrokerageDetailOutput output = new BrokerageDetailOutput();
            Member member = memberService.get((String) resultMap.get("authorId"));
            output.setAuthorName(member.getRealname());
            output.setActualAmount((Float) resultMap.get("actualAmount"));
            output.setFavorerNum((Integer) resultMap.get("favorerNum"));
            output.setApplyDate((Date) resultMap.get("applyDate"));
            output.setCheckDate((Date) resultMap.get("checkDate"));
            output.setFreezeDate((Date) resultMap.get("freezeDate"));
            output.setBrokerage((Float) resultMap.get("brokerage"));
            output.setCheckStatus((Integer) resultMap.get("checkStatus"));
            output.setTitle((String) resultMap.get("title"));
            String projectId = (String) resultMap.get("projectId");
            String allUseTime = projectBizService.getAllUseTime(projectId, null);
            output.setAllUseTime(allUseTime);
            return AjaxResult.success(output);
        } catch (Exception e) {
            logger.error("详情异常", e);
            return AjaxResult.error(999, "详情异常");
        }
    }
}
